package com.zaoke.web.component.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoggerInterceptor implements HandlerInterceptor {

	private static Logger log = LoggerFactory
			.getLogger(LoggerInterceptor.class);
	private static String TRACE_LOG_CALL_SUCCESS_KEY = "TRACE_LOG_CALL_SUCCESS_KEY";
	private static String TRACE_LOG_CALL_CONSUME_KEY = "TRACE_LOG_CALL_CONSUME_KEY";

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Long start = System.nanoTime();
		request.setAttribute(TRACE_LOG_CALL_SUCCESS_KEY, false);
		request.setAttribute(TRACE_LOG_CALL_CONSUME_KEY, start);
		//System.out.println(request);
		//System.out.println(request.getReader().readLine());
		
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		request.setAttribute(TRACE_LOG_CALL_SUCCESS_KEY, true);
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long end = System.nanoTime();
		Long start = (Long) request.getAttribute(TRACE_LOG_CALL_CONSUME_KEY);
		Boolean success = (Boolean) request
				.getAttribute(TRACE_LOG_CALL_SUCCESS_KEY);

		//TODO 
//		StringBuilder logBuilder = new StringBuilder();
//		logBuilder.append(CommonLog.getCommon()).append("|")
//				.append(request.getRequestURI()).append("|")
//				.append(request.getQueryString()).append("|")
//				.append(CommonLog.consumeTime(end, start)).append("|")
//				.append(success);
//		log.info(logBuilder.toString());

	}

}
